package arcane.object.collections;

import java.util.Collection;
import java.util.NoSuchElementException;

public class ListIterator<T> implements java.util.ListIterator<T> {
	T[] list;
	int index;
	int previousIndex;

	public ListIterator(Collection<T> c) {
		this(c.toArray((T[]) new Object[c.size()]));
	}

	public ListIterator(T[] t) {
		list = t;
		index = 0;
		previousIndex = -1;
	}

	public void add(T t) {
		throw new UnsupportedOperationException(
				"Cannot add objects to ListIterator.");
	}

	public boolean hasNext() {
		return index < list.length - 1;
	}

	public boolean hasPrevious() {
		return index > 0;
	}

	public T next() {
		if (hasNext()) {
			previousIndex = index;
			return list[++index];
		} else
			throw new NoSuchElementException("List has no next element.");
	}

	public int nextIndex() {
		return index + 1;
	}

	public T previous() {
		if (hasPrevious()) {
			previousIndex = index;
			return list[--index];
		} else
			throw new NoSuchElementException("List has no previous element.");
	}

	public int previousIndex() {
		return index - 1;
	}

	public void remove() {
		throw new UnsupportedOperationException(
				"Remove operation is not supported.");
	}

	public void set(T t) {
		if (previousIndex >= 0) {
			list[previousIndex] = t;
		} else {
			throw new IllegalStateException(
					"Neither next nor previous have been called!");
		}
	}
}